<template>
    <!-- 挂账支付 --> 
    <div class="jeecg-basic-table jeecg-basic-table-form-container">
      <a-form @keyup.enter.native="searchQuery">
        <a-row :gutter="8" type="flex">
          <a-col flex="135px">
            <a-form-item label="部门" :label-col="{ style: { width: '40px' } }" :wrapper-col="{ span: 18 }">
              <JDictSelectTag
                v-model:value="queryParam.ddlxIds"
                mode="multiple"
                dictCode="ddlxType@ddlxUser"
                placeholder="全部"
                :maxTagCount="0"
                :getPopupContainer="(node) => node.parentNode"
                :dropdownStyle="{ width: '120px', overflow: 'auto' }"
                :dropdownMatchSelectWidth="false"
              />
            </a-form-item>
          </a-col>

          <a-col flex="115px">
            <a-form-item label="方式" :label-col="{ style: { width: '40px' } }" :wrapper-col="{ span: 17 }">
              <a-select v-model:value="queryParam.sffs" class="w80" placeholder="全部" :showArrow="false" :allowClear="false">
                <a-select-option value="1">转账</a-select-option>
                <a-select-option value="3">挂账</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col flex="350px">
            <a-form-item label="审批时间" :label-col="{ style: { width: '70px' } }" :wrapper-col="{ style: { width: '270px' } }">
              <a-date-picker
                v-model:value="queryParam.spsjBegin"
                :disabled-date="disabledStartDate"
                :disabled="begDateDisabled"
                valueFormat="YYYY-MM-DD"
                placeholder=""
                style="width: 123px"
              />
              ~
              <a-date-picker
                v-model:value="queryParam.spsjEnd"
                :disabled-date="disabledEndDate"
                :disabled="begDateDisabled"
                valueFormat="YYYY-MM-DD"
                placeholder=""
                style="width: 123px"
              />
            </a-form-item>
          </a-col>

          <a-col flex="202px">
            <a-form-item label="订单编号" :label-col="{ style: { width: '70px' } }" :wrapper-col="{ span: 17 }">
              <a-input placeholder="" v-model:value="queryParam.orderId"></a-input>
            </a-form-item>
          </a-col>

          <a-col flex="202px">
            <a-form-item label="单位名称" :label-col="{ style: { width: '70px' } }" :wrapper-col="{ span: 17 }">
              <a-input placeholder="" v-model:value="queryParam.dwmc"></a-input>
            </a-form-item>
          </a-col>

          <a-col flex="auto" style="float: right; width: 180px">
            <span style="float: right; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" color="success" @click="searchQuery" preIcon="ant-design:search">查询</a-button>
              <a-button type="default" color="error" @click="handelMerge" preIcon="ant-design:reload-outlined" style="margin-left: 8px">提交</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- table区域-begin -->
    <BasicTable @register="registerTable" :onRowDbClick="handleDblclick" :rowSelection="rowSelection" :loading="false">
      <template #operation="{ text, record }">
        <a-badge :color="statusColor(text, record)" :text="operateTim(text, record)" />
      </template>
    </BasicTable>
    <!-- table区域-end -->

  <!-- 表单区域 -->
  <AccountFlowInterval @register="registerAccountFlowInterval" @success="reload"></AccountFlowInterval>
  <AccountFlowBatchPaymentModal @register="registerAccountFlowBatchPaymentModal" @success="reload"></AccountFlowBatchPaymentModal>
</template>

<script lang="ts" setup name="AccountFlowBatchPaymentList">
  import { ref, computed, unref, reactive, toRaw } from 'vue';
  import { BasicTable, TableAction, ActionItem, BasicColumn } from '/@/components/Table';
  import { useModal } from '/@/components/Modal';
  import { useListPage } from '/@/hooks/system/useListPage';
  import { render } from '/@/utils/common/renderUtils';
  import { paymentList } from '/@/views/full/account/types/accountBatch.api';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useUserStore } from '/@/store/modules/user';
  import { BasicModal, useModalInner } from "/@/components/Modal";

  import moment from 'dayjs';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import AccountFlowInterval from './modules/AccountFlowInterval.vue';
  import AccountFlowBatchPaymentModal from './modules/AccountFlowBatchPaymentModal.vue';

  //初始化 -------------------------------------------------------------
  const { createMessage: $message } = useMessage();
  const userStore = useUserStore();
  // 声明Emits
  const emit = defineEmits(['success', 'register']);

  //表单赋值
  const [registerModal, { closeModal }] = useModalInner(async (data) => {
    //await init(data);
  });

  //定义查询表单，查询条件
  const queryParam = reactive({
    ddlxIds: '',
    stat: '2', //未审
    sffs: '1',
    orderId: '',
    dwmc: '',
    bz: '',
    userIds: '',
    spsjBegin: '',
    spsjEnd: '',
  });

  let isReload = ref(false); //是否有数据操作
  let loading  = ref(true); //

  /* 日期参数 */
  function disabledStartDate(beginDate) {
    const endDate = queryParam.spsjEnd;
    if (!beginDate || !endDate) {
      return false;
    }
    return beginDate.valueOf() > moment(endDate).valueOf();
  }

  function disabledEndDate(endDate) {
    const beginDate = queryParam.spsjBegin;
    if (!endDate || !beginDate) {
      return false;
    }
    return moment(beginDate).valueOf() > endDate.valueOf();
  }

  //转账支付，审核状态为经理时，默认查询日期是； 其它状态
  let begDateDisabled = ref(true);
  let endDateDisabled = ref(true);
  function statSelect(data) {
    console.info('statSelect@@@', data);
    if (data == '2' || data == '') {
      queryParam.spsjBegin = '';
      queryParam.spsjEnd = '';
      begDateDisabled.value = true;
      endDateDisabled.value = true;
    } else {
      var today = moment().format('YYYY-MM-DD');
      queryParam.spsjBegin = today;
      queryParam.spsjEnd = today;
      begDateDisabled.value = false;
      endDateDisabled.value = false;
    }
  }

  //订单列表
  const statusFmt = ({ text }: { text: any }) => {
    if (!text) {
      return;
    }
    const color = text == '2' ? 'red' : text == '3' ? 'green' : 'blue';
    return render.renderTag(render.renderDict(text, 'accountStat'), color);
  };

  //操作人 2经理，3已审，9回退
  const statusColor = (text, record) => {
    let color = '';
    if (record.stat == '2') {
      color = 'green';
    } else if (record.stat == '3') {
      color = 'magenta';
      text = record.shsj;
    } else if (record.stat == '9') {
      color = '#999';
      text = record.spsj;
    }

    if (!text) {
      color = '';
    }
    return color;
  };

  //操作时间
  const operateTim = (text, record) => {
    if (record.stat == '2') {
      text = record.shsj;
    } else if (record.stat == '3' || record.stat == '9') {
      text = record.spsj || record.shsj;
    }
    if (!text) {
      return '';
    } else {
      return moment(text).format('YYYY-MM-DD HH:mm');
    }
  };

  const operator = ({ text, record }) => {
    if (record.stat == '2') {
      text = record.shrName;
    } else if (record.stat == '3' || record.stat == '9') {
      text = record.sprName || record.shrName;
    }
    if (!text) {
      return '';
    } else {
      return text;
    }
  };

  // 支付方式
  const sffsFmt = ({ text }: { text: any }) => {
    if (!text) {
      return;
    }
    const color = text == '1'?'red' : text == '3'? 'green' : 'blue';
    return render.renderTag(render.renderDict(text, 'sffsType'), color);
  };

  //订单列表 - 表头
  const columns: BasicColumn[] = [
    { title: '状态', align: 'center', dataIndex: 'stat', width: 40, customRender: statusFmt },
    { title: '订单号', align: 'center', dataIndex: 'orderId', width: 90, className: 'text-red-500' },
    { title: '部门', align: 'center', dataIndex: 'ddlx', width: 50, customRender: ({ text }) => render.renderDict(text, 'ddlxType') },
    { title: '单位名称', align: 'left', dataIndex: 'pathName', width: 180 },
    { title: '支出金额', align: 'right', dataIndex: 'fkje', width: 80, className: 'text-green-500' },
    { title: '备注', align: 'left', dataIndex: 'bz', width: 150 },
    { title: '提交人', align: 'center', dataIndex: 'realname', width: 55 },
    { title: '提交日期', align: 'center', dataIndex: 'lrsj', width: 100, format: 'date|YYYY-MM-DD HH:mm' },
    { title: "审核人", align:"center", dataIndex:"shrName", width: 55 },
    { title: "审核日期", align:"center", dataIndex:"shsj", width: 100, slots: { customRender: 'operation' } },
  ];

  //初始化 -------------------------------------------------------------

  function searchQuery() {
    setProps({ searchInfo: toRaw(queryParam) });
    reload();
  }

  function searchReset() {
    Object.assign(queryParam, { ddlxIds: '', ddzt: '', ywlx: '' });
    reload();
  }

  function searchMerge() {
    Object.assign(queryParam, { ddlxIds: '', ddzt: '', ywlx: '' });
    reload();
  }

  function handleSummary(tableData: Recordable[]) {
    const res = getRawDataSource();
    if (res) {
      return getRawDataSource().summary;
    } else {
      return [];
    }
  }

  // 列表页面公共参数、方法
  const { prefixCls, tableContext } = useListPage({
    designScope: 'accountBatch-paymentList',
    tableProps: {
      api: paymentList,
      columns: columns,
      showTableSetting: false,
      showIndexColumn: false, //行号
      clickToRowSelect: true, //点击选择
      showActionColumn: false,
      useSearchForm: false,
      showSummary: true,
      resizeHeightOffset: 30,
      summaryFunc: handleSummary,
      beforeFetch: (params) => Object.assign(params, unref(queryParam)),
    },
  });

  //注册table数据
  const [registerTable, { reload, setProps, getRawDataSource, setSelectedRowKeys, redoHeight }, { rowSelection, selectedRowKeys, selectedRows }] = tableContext;

  //详细订单
  const [registerAccountFlowInterval, { openModal: openAccountFlowInterval }] = useModal();

  //双击行
  function handleDblclick(record) {
    //openBusinessOrder(true, record.id);
    var params = Object.assign({}, queryParam);
    params['id'] = record.id;
    params['type'] = 'batchPayment';
    openAccountFlowInterval(true, params);
  }

  //合并支付
  const [registerAccountFlowBatchPaymentModal, { openModal: openAccountFlowBatchPaymentModal }] = useModal();

  //提交
  function handelMerge() {
    //1、获取被选中的行信息
    let rows = unref(selectedRows);
    if (rows.length <= 1) {
      $message.warning('合并支付：最少需要选择2条数据！'); //请勾选不能为空！
      return false;
    }

    //2、判断选中的单位是否是同一家
    var pId = [], ids = '';
    for (var i = 0; i < rows.length; i++) {
      pId.push(rows[i].coopId);
      if (i == 0) {
        ids = rows[i].id;
      } else {
        ids = ids + ',' + rows[i].id;
      }
    }

    let k = false;
    // && userStore.getTenant == 1 作集团系统设置
    if (pId.length > 0 && userStore.getTenant == 1) {
      pId = pId.sort();
      for (var i = 0; i < pId.length - 1; i++) {
        if (pId[i] != pId[i + 1]) {
          $message.warning('合并支付：只能选择相同的单位名称！');
          k = true;
          break;
        }
      }
    }

    if (k) {
      return false;
    } else {
      var params = Object.assign({}, queryParam);
      params['ids'] = ids;
      params['type'] = 'batchPayment';
      openAccountFlowBatchPaymentModal(true, params);
    }
    //console.info(selectedRows)
    //openAccountFlowBatchPaymentModal(true, { ids });
  }

  // Cancel event
  function onClose() {
    //console.info("isReload.value@@@@@@@@", isReload.value)
    if (isReload.value) {
      emit('success');
    }
  }
</script>
<style scoped>
</style>
